<template>
    <div class="population-statistics population-page u-f p-10">
        <div class="flex-3 h100 u-f u-f-column">
            <div class="flex-1" ref="countPastYearsChart">
                
            </div>
            <div class="flex-1" ref="countPopulationPyramidChart">
            </div>
        </div>
        <div class="flex-4 h100 " ref="countChinaChart">

        </div>
        <div class="flex-3 u-f u-f-column h100">
          <div class="flex-1 h100" ref="countDieAgeChart">
          </div>
          <div class="flex-1 h100">
            <div class="h100" ref="countVitalStatisticsChart"></div>
          </div>
        </div>
    </div>
</template>
<script>
import * as echarts from 'echarts'
import chinaJson from '@/data/china.json';
import {recordNumberPeople,getListAge,getListNumberPeople,getDeathOrSurvivalList,getMaleList,getFemaleList,getPoetList,getPoetAgeList} from '@/api/locale-api'


export default {
  name: 'PopulationStatistics',
  data() {
    return {
        ageList:[],
        numberList:[],
        storyList:[],
        deathOrSurvivalList:[],
        maleData:[],
        femaleData:[],
        mapData:[],
        poetAgeList:[]

    }
  },
  created() {
    this.listNumber();
  },
  mounted(){
    // this.initChart();
  },
  methods: {
    listNumber(){
        Promise.all([
      recordNumberPeople(),
      getListAge(),
      getListNumberPeople(),
      getDeathOrSurvivalList(),
      getMaleList(),
      getFemaleList(),
      getPoetList(),
      getPoetAgeList()
    ]).then(([res1, res2, res3,res4,res5,res6,res7,res8]) => {
      if (res1.code === '200') {
        this.storyList = res1.data;
      }
      if (res2.code === '200') {
        this.ageList = res2.data; // 确保这里赋值成功
      }
      if (res3.code === '200') {
        this.numberList = res3.data;
      }
      if(res4.code === '200'){
        this.deathOrSurvivalList = res4.data;
      }
      if(res5.code === '200'){
        this.maleData = res5.data;
      }
      if(res6.code === '200'){
        this.femaleData = res6.data;
      }
      if(res7.code === '200'){
        this.mapData = res7.data;
      }
      if(res8.code === '200'){
        this.poetAgeList = res8.data
      }
      // 在请求数据之后再初始化图表
      this.initChart();
    }).catch(error => {
      console.error("数据请求失败:", error);
    });
    },
    initChart(){
      this.initCountPastYearsChart()
      this.initCountPopulationPyramidChart()
      this.initCountDieAgeChart()
      this.initCountVitalStatisticsChart()
      this.initCountChinaChart()
    },
    initCountPastYearsChart() {
      const countPastYearsChartInstance = echarts.init(this.$refs.countPastYearsChart)
      var option = {
        title: {
            text: '唐朝历年人数统计', 
            left: 'center',
            top: '6%',
            textStyle: {
                color: '#333', 
                fontSize: 16, 
                fontWeight: 'bold', 

            }
        },
        tooltip: {
            trigger:'axis',
            position: function (point, params, dom, rect, size) {
                // 固定在图表右侧，适当调整 top 值
                return ['90%', '10%'];
            },
            formatter: (params) =>  {
                return params[0].name + '年: ' + params[0].value + '（人）<br>'+this.storyList[params[0].dataIndex].story;
                // if (params[0].dataIndex === 2) { // Check for the year 650
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元649年，李治继位';
                // }else if (params[0].dataIndex === 6) { // Check for the year 690
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元690年，武则天继位';
                // }else if (params[0].dataIndex === 8) { 
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元712年，李隆基继位';
                // }else if (params[0].dataIndex === 12) { 
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元755年，安史之乱开始';
                // }else if (params[0].dataIndex === 13) { 
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元763年，安史之乱结束';
                // }else if (params[0].dataIndex === 20) { 
                //     return params[0].name + '年: ' + params[0].value + '（人）<br>公元835年，甘露之变';
                // }else {
                //     return params[0].name + '年: ' + params[0].value + '（人）';
                // }
            }
        },
        
        xAxis: {
            name:'年份',
            // data: [630,"640","650","660","670","680","690","700","710","720","730","740","750","760","770","780","790","800","810","820","830","840","850","860","870","880","890","900"],
            data:this.ageList,
            axisLine: {
                lineStyle: {
                    color: '#151d29',
                    width: 2
                }
            }
        },
        yAxis: [ {
            type: 'value',
            max: function (value) {
        // 例如最大值是 3470000，那我们向上取整为 4000000
        return Math.ceil(value.max / 100000) * 100000;
    },
        interval: function (value) {
        // 动态设置 interval，比如最大值除以 5
        return Math.ceil(value.max / 5 / 1000) * 1000;
    },
            name: '数量统计',
            show:true,
            // interval: 400,
            axisLine: {
                lineStyle: {
                    color: '#151d29',
                    width: 2
                }
            }
        }
      ],
        series: [{
            name: '数量统计',
            type: 'bar',
            barWidth : '70%',
            showBackground: true,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#d2a36c' },
                { offset: 0.5, color: '#d5c8a0' },
                { offset: 1, color: '#dfd6b8' }
                ])
            },
            emphasis: {
                itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#ba5b49' },
                    { offset: 0.7, color: '#d2a36c' },
                    { offset: 1, color: '#dfd6b8' }
                ])
                }
            },
            // data: [1357, 969, 1063, 1355, 1444, 1350, 1438, 1412, 1760, 1508, 1451, 1817, 1532, 1431, 1811, 1780, 1830, 1530, 1509, 1401, 1204, 1053, 380, 76, 36, 19, 12, 6],
            data:this.numberList,
            yAxisIndex: 0
        },{
            type: 'line',
            smooth:true,
            // data: [1357, 969, 1063, 1355, 1444, 1350, 1438, 1412, 1760, 1508, 1451, 1817, 1532, 1431, 1811, 1780, 1830, 1530, 1509, 1401, 1204, 1053, 380, 76, 36, 19, 12, 6],
            data:this.numberList,
            yAxisIndex: 0
        }],
        dataZoom: [
            {
                show: true,
                start: 0,
                end: 100
            },
            {
                type: 'inside',
                start: 0,
                end: 100
            }
        ]
      };
      countPastYearsChartInstance.setOption(option)
    },


    initCountPopulationPyramidChart(){
      const chartInstance = echarts.init(this.$refs.countPopulationPyramidChart)

      var categories = [
        '0-4', '5-9', '10-14', '15-19',
        '20-24', '25-29', '30-34', '35-39', '40-44',
        '45-49', '50-54', '55-59', '60-64', '65-69',
        '70-74', '75-79', '80-84', '85-89', '90-94',
        '95-99', '100 + '
      ];

    //   var maleData = [
    //       14, 4, 10, 66,
    //       54, 98, 116, 144,
    //       210, 358, 484, 562,
    //       706, 671, 566, 345,
    //       200, 92, 24, 12,
    //       0.0
    //   ];
        var maleData = this.maleData.map(item =>item.number);
    //   var femaleData = [
    //       0, 0, 0, 15, 19,
    //       29, 30, 25, 27, 34,
    //       36, 48, 36, 56, 60,
    //       48, 36, 12, 8, 0,
    //       0.0
    //   ];

    var femaleData =this.femaleData.map(item => item.number);
      var maleTotal = maleData.map(function(x) {
          return Math.abs(x);
      }).reduce(function(a, b) {
          return a + b;
      });
      var femaleTotal = femaleData.map(function(x) {
          return Math.abs(x);
      }).reduce(function(a, b) {
          return a + b;
      });

      var malePercentage = maleData.map(function(x){
          return -(x / maleTotal * 100); 
      });

      var femalePercentage = femaleData.map(function(x){
          return x / femaleTotal * 100;
      });
      var option = {
        title: {
            text: '唐朝人口金字塔',
            left: 'center',
            top: '6%',
            textStyle: {
                color: '#333', 
                fontSize: 16, 
                fontWeight: 'bold', 
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                return params[0].name + '<br/>' +
                    params[0].seriesName + ': ' + Math.abs(maleData[params[0].dataIndex]) + ' (' + Math.abs(params[0].data).toFixed(2) + '%)' + '<br/>' +
                    params[1].seriesName + ': ' + Math.abs(femaleData[params[0].dataIndex]) + ' (' + Math.abs(params[1].data).toFixed(2) + '%)';
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        legend: {
            data: ['男性', '女性'],
            align: 'left',
            top: '15%',
            right: -5
        },
        xAxis: {
            type: 'value',
            axisLabel: {
                formatter: function (value) {
                    return Math.abs(value)+'%';
                }
            }
        },
        yAxis: {
            type: 'category',
            data: categories
        },
        series: [
            {
                name: '男性',
                type: 'bar',
                stack: 'total',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#3d8e86' },
                        { offset: 0.5, color: '#5da39d' },
                        { offset: 1, color: '#88bfb8' }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: malePercentage
            },
            {
                name: '女性',
                type: 'bar',
                stack: 'total',
                emphasis: {
                    focus: 'series'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#d2a36c' },
                        { offset: 0.5, color: '#d5c8a0' },
                        { offset: 1, color: '#dfd6b8' }
                    ])
                },
                data: femalePercentage
            }
        ]
      };
      chartInstance.setOption(option)
    },
    initCountDieAgeChart(){
      const chartInstance = echarts.init(this.$refs.countDieAgeChart)
        const data=   JSON.parse(JSON.stringify(this.poetAgeList));
       

      const datas = [
        [
            [2, 1],
            [3, 1],
            [4, 2],
            [5, 4],
            [6, 2],
            [7, 1],
            [8, 2],
            [9, 5],
            [10, 3],
            [11, 4],
            [12, 6],
            [13, 9],
            [14, 5],
            [15, 9],
            [16, 25],
            [17, 26],
            [18, 18],
            [19, 31],
            [20, 33],
            [21, 31],
            [22, 29],
            [23, 39],
            [24, 31],
            [25, 33],
            [26, 31],
            [27, 39],
            [28, 33],
            [29, 28],
            [30, 40],
            [31, 37],
            [32, 47],
            [33, 36],
            [34, 54],
            [35, 46],
            [36, 42],
            [37, 48],
            [38, 47],
            [39, 50],
            [40, 50],
            [41, 45],
            [42, 60],
            [43, 56],
            [44, 71],
            [45, 57],
            [46, 64],
            [47, 79],
            [48, 72],
            [49, 99],
            [50, 102],
            [51, 89],
            [52, 120],
            [53, 117],
            [54, 103],
            [55, 164],
            [56, 115],
            [57, 152],
            [58, 137],
            [59, 137],
            [60, 160],
            [61, 158],
            [62, 157],
            [63, 144],
            [64, 139],
            [65, 162],
            [66, 147],
            [67, 149],
            [68, 128],
            [69, 139],
            [70, 129],
            [71, 119],
            [72, 141],
            [73, 118],
            [74, 125],
            [75, 120],
            [76, 92],
            [77, 88],
            [78, 70],
            [79, 80],
            [80, 62],
            [81, 76],
            [82, 46],
            [83, 51],
            [84, 40],
            [85, 34],
            [86, 21],
            [87, 22],
            [88, 21],
            [89, 16],
            [90, 13],
            [91, 4],
            [92, 7],
            [93, 12],
            [94, 4],
            [95, 4],
            [96, 4],
            [97, 3],
            [99, 4],
            [101, 2],
            [103, 1],
            [107, 1],
            [108, 1],
            [112, 1],
            [120, 1]
          ]
      ];
    console.log(data);
      const option = {
        title: {
            text: '唐代人物享年数据分布',
            left: 'center',
            top: '1%',
            textStyle: {
                color: '#333', 
                fontSize: 16, 
                fontWeight: 'bold', 
            }
        },
        tooltip: {
            trigger:'axis',
            formatter: function (params) {
                return params[0].value[0] + '岁:' + params[0].value[1] + '（人）';
            }
        },
        grid: {
            left: '8%',
            top: '10%'
        },
        xAxis: {
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        yAxis: {
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            },
            scale: true
        },
        series: [
            {
                name: '人数',
                data: data[0],
                type: 'scatter',
                symbolSize: function (data) {
                    return Math.sqrt(data[1]) * 1.6;
                },
                itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(190, 210, 187, 0.6)',
                    shadowOffsetY: 5,
                    color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                        {
                            offset: 0,
                            color: '#3d8e86' 
                        },
                        {
                            offset: 1,
                            color: '#88bfb8'
                        }
                    ]),
                },
                emphasis: {
                  color: 'rgba(200, 107, 55, 0.6)' 
                },
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ],
                    lineStyle: {
                        color: '#a04c3b' // 指定平均线的颜色
                    }
                }
            }
        ]
      };
      chartInstance.setOption(option)
    },
    initCountVitalStatisticsChart(){
      const chartInstance = echarts.init(this.$refs.countVitalStatisticsChart)
      const age=  this.deathOrSurvivalList.map(item => item.age);
      const survival=  this.deathOrSurvivalList.map(item => item.survival);
      const death=  this.deathOrSurvivalList.map(item => item.death);
      let xAxisData = age;
      let data1 = survival;
      let data2 = death;
      const emphasisStyle = {
          itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0,0,0,0.3)'
          }
      };

      const option = {
        title: {
            text: '唐朝历年出生死亡人数统计', 
            left: '15%',
            top: '0.5%',
            textStyle: {
                color: '#333', 
                fontSize: 16, 
                fontWeight: 'bold', 
            }
        },
        legend: {
            data: ['出生', '死亡'],
            left: 'center',
            top: '12%'
        },
        brush: {
            toolbox: ['rect', 'clear'],
            xAxisIndex: 0
        },
        toolbox: {
            feature: {
                magicType: {
                    type: ['stack', 'tiled'] 
                }
            }
        },
        tooltip: {},
        xAxis: {
            data: xAxisData,
            name: '年份',
            axisLine: { 
                lineStyle: {
                    color: '#151d29',
                    width: 2
                },
            },
            axisLabel: {
                color: '#333', 
                fontSize: 8,
                rotate: 15,  
            }
        },
        yAxis: {
            name: '人数',
            axisLine: {
                lineStyle: {
                    color: '#151d29',
                    width: 2
                }
            },
            axisLabel: {
              color: '#333', 
              fontSize: 10
            }
        },
        grid: {
            bottom: 50
        },
        series: [
            {
                name: '出生',
                type: 'bar',
                barWidth : '35%',
                barCategoryGap: '0', // 设置柱体无间隔
                stack: 'one',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#3d8e86' },
                        { offset: 0.5, color: '#5da39d' },
                        { offset: 1, color: '#88bfb8' }
                    ]),
                    
                },
                emphasis: emphasisStyle,
                data: data1
            },
            {
                name: '死亡',
                type: 'bar',
                barWidth : '35%',
                barCategoryGap: '0', // 设置柱体无间隔
                stack: 'one',
                showBackground: true,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#d2a36c' },
                        { offset: 0.5, color: '#d5c8a0' },
                        { offset: 1, color: '#dfd6b8' }
                    ]),
                    
                },
                emphasis: emphasisStyle,
                data: data2 
            }
        ]
      };
      chartInstance.setOption(option)
    },
    initCountChinaChart(){
        const name = '唐朝历史人物分布'
        echarts.registerMap('china', chinaJson)
        const chartInstance = echarts.init(this.$refs.countChinaChart)
        const mapData=   JSON.parse(JSON.stringify(this.mapData));
       
        // let mapData = [
        //     {
        //         name: "河南省",
        //         value: 14827
        //     },
        //     {
        //         name: "陕西省",
        //         value: 10333
        //     },
        //     {
        //         name: "河北省",
        //         value: 4490
        //     },
        //     {
        //         name: "山西省",
        //         value: 4165
        //     },
        //     {
        //         name: "甘肃省",
        //         value: 2147
        //     },
        //     {
        //         name: "江苏省",
        //         value: 2102
        //     },
        //     {
        //         name: "山东省",
        //         value: 1774
        //     },
        //     {
        //         name: "浙江省",
        //         value: 1266
        //     },
        //     {
        //         name: "湖北省",
        //         value: 615
        //     },
        //     {
        //         name: "四川省",
        //         value: 579
        //     },
        //     {
        //         name: "安徽省",
        //         value: 558
        //     },
        //     {
        //         name: "广东省",
        //         value: 540
        //     },
        //     {
        //         name: "江西省",
        //         value: 372
        //     },
        //     {
        //         name: "湖南省",
        //         value: 345
        //     },
        //     {
        //         name: "北京市",
        //         value: 315
        //     },
        //     {
        //         name: "广西壮族自治区",
        //         value: 258
        //     },
        //     {
        //         name: "福建省",
        //         value: 188
        //     },
        //     {
        //         name: "内蒙古自治区",
        //         value: 97
        //     },
        //     {
        //         name: "天津市",
        //         value: 75
        //     },
        //     {
        //         name: "新疆维吾尔自治区",
        //         value: 67
        //     },
        //     {
        //         name: "上海市",
        //         value: 45
        //     },
        //     {
        //         name: "重庆市",
        //         value: 42
        //     },
        //     {
        //         name: "宁夏回族自治区",
        //         value: 26
        //     },
        //     {
        //         name: "海南省",
        //         value: 10
        //     },
        //     {
        //         name: "辽宁省",
        //         value: 8
        //     },
        //     {
        //         name: "云南省",
        //         value: 6
        //     },
        //     {
        //         name: "贵州省",
        //         value: 2
        //     },
        //     {
        //         name: "台湾省",
        //         value: 0
        //     },
        //     {
        //         name: "西藏自治区",
        //         value: 0
        //     },
        //     {
        //         name: "青海省",
        //         value: 0
        //     },
        //     {
        //         name: "吉林省",
        //         value: 0
        //     },
        //     {
        //         name: "黑龙江省",
        //         value: 0
        //     },
        //     {
        //         name: "香港特别行政区",
        //         value: 0
        //     },
        //     {
        //         name: "澳门特别行政区",
        //         value: 0
        //     },
        // ]
        var option = {
            title: {
                text: name,
                left: 'center',
                top: '6%',
            },
            //鼠标经过展示数据方法
            tooltip: {
                triggerOn: "mousemove",
                formatter: function (params) {
                    if (isNaN(params.value)) {
                        params.value = 0
                    }
                    var html = '<span>' + params.name + '：</span><br/>'
                    html += '<span>值：' + params.value + '</span><br/>'
                    return html
                },
                backgroundColor: 'rgba(29, 38, 71)',
                // 额外附加的阴影
                extraCssText: 'box-shadow:0 0 4px rgba(11, 19, 43,0.8)',
            },
            geo: {
                show: true,
                top: '10%',
                map: 'china',
                label: {
                    normal: {
                        show: false
                    },
                    emphasis: {
                        show: true,
                        color: "#31322c",
                    }
                },
                roam: false,
                itemStyle: {
                    normal: {
                        areaColor: '#fff',
                        borderColor: '#686a67',
                    },
                    emphasis: {
                        areaColor: '#00828B',
                    }
                },
            },
            //进行气泡标点
            series: [
                {
                    type: 'map',
                    map: mapData,
                    geoIndex: 0,
                    aspectScale: 0.75, //长宽比
                    animation: true,
                    data: mapData
                },
            ],
            // 添加色块指示
            visualMap: {
                min: 0,
                max: 15000,
                right: '65%',
                bottom: '1%',
                showLabel: true,
                text: ['High', 'Low'],
                seriesIndex: [0],
                itemHeight: 10,
                itemWidth: 10,
                orient: 'vertical',
                align: 'auto',
                show: true,
                borderWidth: 1,
                borderColor: '#ccc',
                textStyle: {
                    color: '#333'
                },
                // 设置颜色标注
                pieces: [
                    {gt: 12000, color: '#b0112f'}, 
                    {gt: 10000, lte: 12000, color: '#c34654'}, 
                    {gt: 4000, lte: 10000, color: '#ca5860'}, 
                    {gt: 2000, lte: 4000, color: '#df928a'}, 
                    {gt: 1000, lte: 2000, color: '#e3a89a'}, 
                    {gt: 600, lte: 1000, color: '#eabdaa'}, 
                    {gt: 300, lte: 600, color: '#f3dabc'},
                    {gt: 50, lte: 300, color: '#f8ecd1'},
                    {gt: 1, lte: 50, color: '#fcf9e5'}
                ],
                
            }
        };
        if (option && typeof option === 'object') {
            chartInstance.setOption(option);
        }
        window.addEventListener('resize', chartInstance.resize);
    }
  }
}
</script>
<style lang="scss" scoped>
.population-statistics {
    height: calc(100vh - 60px);
}
</style>